﻿<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>{$Think.session.user.p_u_id|get_web_f_mesage}</title>
  <link rel="stylesheet" href="__PUBLIC__/script/jquery-weui/dist/lib/weui.min.css">
  <link rel="stylesheet" href="__PUBLIC__/script/jquery-weui/dist/css/jquery-weui.min.css">
  <link rel="stylesheet" href="__PUBLIC__/styles/base.css">
  <link rel="stylesheet" href="__PUBLIC__/styles/new_pingu1.css">
  <script src="https://cdn.jsdelivr.net/npm/babel-polyfill/dist/polyfill.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/jquery"></script>
  <script src="__PUBLIC__/script/pub/qudao_type.js"></script>
  <script src="__PUBLIC__/script/pub/chanpin_type.js"></script>
  <style>
    ::-webkit-scrollbar {
      display: none;
    }
  </style>
</head>
<body>
  <div class="hidden_form">
    <input type="hidden" name='模糊搜索表单真正提交地址' value="{:U('WebUser/next_pingu')}" id='form_action'>
    <input type="hidden" name='模糊搜索表单真正提交地址' value="{:U('WebUser/next_pingu_alt')}" id='next_pingu_alt'>
    <input type="hidden" name='地区值换渠道and小类' value="{:U('WebUser/ajax_new_pingu')}" id='ajax_new_pingu'>
    <input type="hidden" name='获取大类利息额度' value="{:U('WebUser/new_fz_biaoqian')}" id='new_fz_biaoqian'>
    <form autocomplete="off" action="" method="post" id = 'hidden_form_1'></form>
  </div>
  <div class="container">
    <div class="header">{$Think.session.user.p_u_id|get_web_f_mesage}</div>
    <div class="message_box">
        <!-- 表单 -->
        <div class="weui-cells weui-cells_form">

          <!-- 选择地区 -->
          <div class="weui-cell local">
            <div class="time_line">
              <span class="round_number">①</span>
            </div>
            <div class="weui-cell__hd">
                <label for="city-picker" class="weui-label">选择申贷地点</label>
            </div>
            <div class="weui-cell__bd">
                <input form="gen_form" name = 'daikuan_local' type="text" id='city-picker' class="weui-input" placeholder="请选择地址" value="广东省 深圳市"/>
            </div>
          </div>

          <!-- 渠道类型 -->
          <div class="weui-cell qudao_type">
            <div class="time_line time_line_both">
              <span class="round_number">②</span>
            </div>
            <div class="weui-cell__hd">
                <label for="qudao-type-picker" class="weui-label">选择渠道类型</label>
            </div>
          </div>
          <div class="weui-cell tag_wrap timeline_no_number" id='qudao_leixing'>

            <!-- <volist name='qudao_list' id='vo'>
            <div class="tag_container">
              <input form='hidden_form_1' value = '{$vo.qudao_type}' type="checkbox" name="qudao_type" id="check_{$key}" class="check_tag qudao_type_item">
              <label for="check_{$key}" class="label_check_tag"><span><span>{$vo.qudao_type}</span></span></label>
            </div>
            </volist> -->

          </div>

          <!-- 产品类型 -->

          <div class="weui-cell chanpin_type">
            <div class="time_line time_line_top">
              <span class="round_number">③</span>
            </div>
            <div class="weui-cell__bd">
                <label for="" class="weui-label block_cell">选择产品类型</label>
            </div>
          </div>
          <volist name='biaoqian' id='vo' key='key'>
            <div class="weui-cell chanpin_type">
              <div class="weui-cell__bd">
                  <label for="chanpin_type_hidden_checkbox_{$key}" class="weui-label whole_line_label" inori-data="{$vo.id}">
                    <!-- {$vo.name}<div class="inline_lixi"><span class="js-min_lixi">0.45%</span>-<span class="js-max_lixi">0.88%</span> / <span class="js-min_edu">50万</span>-<span class="js-max_edu">3000万</span></div> -->
                    {$vo.name}<div class="inline_lixi">0.45%-0.88% / 50万-3000万</div>
                  </label>
              </div>
            </div>
            <div style='margin-left:15px;'>
              <input type="checkbox" name='不提交的按钮，指示折叠用' form='not_submit' id='chanpin_type_hidden_checkbox_{$key}' class="chanpin_type_hidden_checkbox">
              <div class="weui-cell chanpin_type_tag_wrap tag_wrap_{$key}" inori-replace-id="{$vo.id}">
                <!-- <volist name="vo.xb" id='val' key='k'>
                  <div class="tag_container">
                    <input form='hidden_form_1' value='{$val.id}' type="checkbox" name="chanpin_type_{$vo.name}" id="chanpin_type_{$val.id}_{$k}" class="check_tag chanpin_type_item">
                    <label for="chanpin_type_{$val.id}_{$k}" class="label_check_tag"><span><span>1</span></span></label>
                  </div>
                </volist> -->
              </div>
            </div>
          </volist>
          <!-- 产品类型 -->

        </div>
    </div>

    <div style="height:5vh;width:100%;"></div>

    <div class="weui-flex button_container">
      <div class="weui-flex__item"><a href="javascript:void(0);" data-target="#kehu_type_popup" onclick="popupScript(this, event)" class="weui-btn weui-btn_primary">下一步</a></div>
      <div class="weui-flex__item"><a href="javascript:void(0);" class="weui-btn weui-btn_warn" onclick="fall_back(this, event)">返回</a></div>
    </div>
  </div>


  <!-- 弹层 -->
  <div id="kehu_type_popup" class="weui-popup__container popup-bottom">
    <div class="weui-popup__overlay"></div>
    <div class="weui-popup__modal">
      <div class="toolbar">
        <div class="toolbar-inner">
          <a href="javascript:;" class="picker-button close-popup">关闭</a>
          <h1 class="title">选择客户群体</h1>
        </div>
      </div>
      <div class="modal-content">
        <div class="weui-grids">
          <a href="javascript:void(0)" onclick="postThis(this, '必须工薪', event)" class="weui-grid js_grid">
            <div class="weui-grid__icon">
              <img src="__PUBLIC__/res/u589.png" alt="u589">
            </div>
            <div class="weui-grid__label">
              工薪族
            </div>
          </a>
          <a href="javascript:void(0)" onclick="postThis(this, '必须自雇', event)" class="weui-grid js_grid">
            <div class="weui-grid__icon">
              <img src="__PUBLIC__/res/u591.png" alt="u591">
            </div>
            <div class="weui-grid__label">
              自雇人士
            </div>
          </a>
          <a href="javascript:void(0)" onclick="postThis(this, 'ziyou', event)" class="weui-grid js_grid">
            <div class="weui-grid__icon">
              <img src="__PUBLIC__/res/u593.png" alt="u593">
            </div>
            <div class="weui-grid__label">
              自由职业/无业
            </div>
          </a>
        </div>
      </div>
    </div>
  </div>
  <!-- end 弹层 -->
  <script src="__PUBLIC__/script/common.js" common-data-1="{:U('Mix/dest')}"></script>
  <script src="__PUBLIC__/script/jquery-weui/dist/js/jquery-weui.min.js"></script>
  <script src="__PUBLIC__/script/jquery-weui/dist/js/city-picker.min.js"></script>
  <script id = 'picker-script'>
  </script>
  <script>
    $(document).ready(() => {
      $.closePopup()
    })
    function showToptip (msg) {
      $.toptip(msg, 'success');
    }
    function postThis (_this,type, evt) {
      const isLessPinggu = sessionStorage.getItem('less_pinggu') === 'true'
      if($(`[name='qudao_type']:checked`).length === 0 && !isLessPinggu) {
        $.closePopup()
        $('.close-popup').click()
        $.toptip('请至少选择一项渠道类型', 'warning')
        evt.preventDefault()
        throw new Error('没有选择渠道类型')
      } else if($(`.chanpin_type_item:checked`).length === 0 && !isLessPinggu) {
        $.closePopup()
        $('.close-popup').click()
        $.toptip('请至少选择一项产品类型', 'warning')
        evt.preventDefault()
        throw new Error('没有选择产品类型')
      }
      let TempName
      let TempValue
      let Temp
      let TempQudaoTypeValue = ''
      let TempChanpinTypeName = ''
      let TempChanpinTypeValue = ''
      let formAction

      if (isLessPinggu) {
        formAction = $('#next_pingu_alt').val()
      } else formAction = $('#form_action').val()
      /* 储存本页数据 */
      let sessionValue = $('#hidden_form_1').serializeArray().concat({name: $('#city-picker').attr('name'), value: $('#city-picker').val()})
      let wholeFormValue = sessionStorage.getItem('rawFormData')
      wholeFormValue = JSON.parse(wholeFormValue)
      wholeFormValue = wholeFormValue.concat(sessionValue)
      sessionStorage.setItem('rawFormData', JSON.stringify(wholeFormValue))
      sessionStorage.setItem('rawFormData_2', JSON.stringify(sessionValue))
      // 即将给DIY表单用
      if ($(`[name='qudao_type_only_one']`).length > 0) {
        // 代表下一页肯定是alt
        const qudao = $(`[name='qudao_type_only_one']:checked`).attr('id')
        const qudao_value = $(`[for='${qudao}']`).text()
        const chanpin = $(`[name='chanpin_type_only_one']:checked`).attr('id')
        const chanpin_value = $(`[for='${chanpin}']`).text()
        sessionStorage.setItem(`nextAlt`, `${qudao_value} - ${chanpin_value}`)
      }
      /* end 储存本页数据 */
      $('body').append(`<form autocomplete="off" id='gen_form' action='${formAction}' method='post'></form>`)
      if (type === 'ziyou') {
        Temp = `<input type="hidden" name='0[0]' form='gen_form' value='0' ><input type="hidden" name='0[1]' form='gen_form' value='自由职业' >`
      } else {
        Temp = `<input type="hidden" name='0' form='gen_form' value='${type}' >`
      }
      $('#gen_form').append(Temp)

      // 修改地区
      let localValue = $('#city-picker').data('picker').value
      $('#city-picker').val(localValue)
      $('#city-picker').attr('name', `1`)

      // 显示原来的数据
      let dirValue = $('#hidden_form_1').serializeArray()
      $.each(dirValue, function (index, item) {
        if (item.name.indexOf('qudao_type') > -1) {
          TempQudaoTypeValue === '' ? TempQudaoTypeValue = item.value : TempQudaoTypeValue += `,${item.value}`
        } else if (item.name.indexOf('chanpin_type') > -1) {
          if (TempChanpinTypeName.indexOf(item.name.replace(/chanpin_type_/,'')) === -1) {
            TempChanpinTypeName === '' ? TempChanpinTypeName = item.name.replace(/chanpin_type_/,'') : TempChanpinTypeName += `,${item.name.replace(/chanpin_type_/,'')}`
          }
          TempChanpinTypeValue === '' ? TempChanpinTypeValue = item.value : TempChanpinTypeValue += `,${item.value}`
        }
      })

      let tempInput = `<input type="hidden" name='2' form='gen_form' value='${TempQudaoTypeValue}' >
      <input type="hidden" name='3[0]' form='gen_form' value='${TempChanpinTypeName}' >
      <input type="hidden" name='3[1]' form='gen_form' value='${TempChanpinTypeValue}' >`
      $('#gen_form').append(tempInput)
      sessionStorage.setItem('newPingu', JSON.stringify( $('#gen_form').serializeArray() ))
      $.closePopup()
      // 增加提示
      $.toptip('即将提交', 'success')
      setTimeout(function(){
        $('#gen_form').submit()
      }, 0)
    }
  </script>



  <script id="fallBackScript">
    /* 返回上一页 */
    function fall_back (_this, evt) {
      // window.history.go(-1)
      location.href = `{:U("Wchat/main")}`
      // 通过再提交一次表单的方式来返回上一页
    }
  </script>
  <!-- 弹层逻辑 -->
  <script>
    function popupScript (_this, evt) {
      const isLessPinggu = sessionStorage.getItem('less_pinggu') === 'true'
      /* 至少选一项 */
      if($(`[name='qudao_type']:checked`).length === 0 && !isLessPinggu) {
        $.toptip('请至少选择一项渠道类型', 'warning')
        throw new Error('没有选择渠道类型')
      } else if($(`.chanpin_type_item:checked`).length === 0 && !isLessPinggu) {
        $.toptip('请至少选择一项产品类型', 'warning')
        throw new Error('没有选择产品类型')
      } else {
        let id = $(_this).attr('data-target')
        $(`${id}`).popup()
      }
    }
  </script>

  <!-- 回填 -->
  <script>
    $(document).ready( () => {
      let myValue = sessionStorage.getItem('rawFormData_2')
      const isLessPinggu = sessionStorage.getItem('less_pinggu') === 'true'
      if (myValue !== undefined && myValue !== null && myValue !== '[]') {
        try{
          myValue = JSON.parse(myValue)
        } catch (e) {
          throw e
        }
        sessionStorage.setItem('need_to_rewrite', '1')
        for( let item of myValue ) {
          let name = item.name
          let value = item.value
          if (name === 'daikuan_local') {
            $("#city-picker").attr('value', value)
          } else {
            // $(`[name='${name}'][value='${value}']`).prop('checked', true)
            ;
          }
        }
        sessionStorage.setItem('rawFormData', sessionStorage.getItem('rawFormData_1'))
      }
      $("#city-picker").cityPicker({
        title: "请选择申贷地点",
        showDistrict: false,
        onClose: (picker, values, displayValues) => {
          console.log(`${picker.value[0]}, ${picker.value[1]}`)
          const ajaxURL = String($(`#ajax_new_pingu`).val())
          let qudaoArray = []
          let xiaoleiArray = {
            id: [],
            name: [],
            value: [],
            fid: [],
            fidName: []
          }
          let qudaoLeixingTempl = ``
          let xiaoleiTempl = {}
          $.ajax(ajaxURL, {
            method: 'post',
            data: {web_city_id: `${picker.value[1]}`},
            beforeSend: () =>{
              $.toptip(`地区选择成功，正在请求对应小类。。。`, `success`)
              // $('.inline_lixi span[data]').text(null)
              $('.button_container').css('display', 'none')
              // 请求发送就要清除渠道和小类
              // 清除渠道类型
              $('#qudao_leixing').empty()
              // 先去除当前所有小类
              $(`.chanpin_type_tag_wrap .tag_container`).each((index, item) => {
                $(item).remove()
              })
            }
          }).fail((err) => {
            $.toptip(`请求小类数据失败！请检查网络`, `error`)
            throw err
          }).done((res) => {
            $('.button_container').css('display', 'flex')
            if (String(res.code) === '1') {
              if (res.data[0] === null || res.data[1].length === 0) {
                $.toptip(`对应筛选条件不足，无法筛选产品！请选择其他地区`, `error`)
                throw new Error(`小类数据异常`)
              }
            } else {
              $.toptip(`请求小类数据时服务器响应异常：${res.message}`, `error`)
              throw new Error(`小类数据异常`)
            }
          }).done((res) => {
            // 以上操作任意一个出错就不会执行到这一行
            // 是否是单选
            const iSlessPinggu = sessionStorage.getItem('less_pinggu') === 'true'
            let uniqudaoArray = []
            // 渠道Type数据
            $.each(res.data[1], (index, item) => {
              if (qudaoArray.indexOf(item.qudao_type) === -1) {
                qudaoArray.unshift(item.qudao_type)
                uniqudaoArray.unshift(item)
              }
            })
            // 小类标签数据
            $.each(res.data[0], (index, item) => {
              let fid = ``
              if (xiaoleiArray.id.indexOf(item.id) === -1) {
                xiaoleiArray.id.push(item.id)
                xiaoleiArray.name.push(item.name)
                xiaoleiArray.value.push(item.id)
                xiaoleiArray.fid.push(item.f_id.id)
                fid = item.f_id.id
                xiaoleiArray.fidName.push(item.f_id.name)
              }
              if (xiaoleiTempl[fid] === undefined) xiaoleiTempl[fid] = ``
            })
            // 数组组装完毕，开始生成相应结构替换
            // 渠道类型
            // id= 'qudao_leixing'
            // <volist name='qudao_list' id='vo'>
            // <div class="tag_container">
            //   <input form='hidden_form_1' value = '{$vo.qudao_type}' type="checkbox" name="qudao_type" id="check_{$key}" class="check_tag qudao_type_item">
            //   <label for="check_{$key}" class="label_check_tag"><span><span>{$vo.qudao_type}</span></span></label>
            // </div>
            // </volist>
            //

              if (iSlessPinggu) {
                $.each(qudaoArray, (index, item) => {
                  if (uniqudaoArray[index].m_data === undefined) {
                    uniqudaoArray[index].m_data = {
                      new_max_ed: '**',
                      new_max_lx: '0.00',
                      new_min_ed: '**',
                      new_min_lx: '0.00'
                    }
                  }
                  qudaoLeixingTempl += `
                    <div class="tag_container">
                      <input form='hidden_form_1' value = '${item}' type="radio" name="qudao_type_only_one" id="check_${index}" class="check_tag qudao_type_item">
                      <label for="check_${index}" class="label_check_tag"><span><span>${item}</span></span></label>
                      <div class='tag_addon_msg'><span>${uniqudaoArray[index].m_data.new_min_lx}%-${uniqudaoArray[index].m_data.new_max_lx}%</span></div>
                    </div>
                  `.trim()
                })
              } else {
                $.each(qudaoArray, (index, item) => {
                  if (uniqudaoArray[index].m_data === undefined) {
                    uniqudaoArray[index].m_data = {
                      new_max_ed: '**',
                      new_max_lx: '0.00',
                      new_min_ed: '**',
                      new_min_lx: '0.00'
                    }
                  }
                  qudaoLeixingTempl += `
                    <div class="tag_container">
                      <input form='hidden_form_1' value = '${item}' type="checkbox" name="qudao_type" id="check_${index}" class="check_tag qudao_type_item">
                      <label for="check_${index}" class="label_check_tag"><span><span>${item}</span></span></label>
                      <div class='tag_addon_msg'><span>${uniqudaoArray[index].m_data.new_min_lx}%-${uniqudaoArray[index].m_data.new_max_lx}%</span></div>
                    </div>
                  `.trim()
                })
              }
            // 小类标签类型
            // .whole_line_label[inori-data="{$vo.id}"] => for='chanpin_type_hidden_checkbox_{$key}' => id='chanpin_type_hidden_checkbox_{$key}' => .next() => .append()
            // <volist name="vo.xb" id='val' key='k'>
            // <div class="tag_container">
            //   <input form='hidden_form_1' value='{$val.id}' type="checkbox" name="chanpin_type_{$vo.name}" id="chanpin_type_{$val.id}_{$k}" class="check_tag chanpin_type_item">
            //   <label for="chanpin_type_{$val.id}_{$k}" class="label_check_tag"><span><span>{$val.name}</span></span></label>
            // </div>
            // </volist>
            //
            if (iSlessPinggu) {
              $.each(xiaoleiArray.id, (index, item) => {
                const value = {
                  id: xiaoleiArray.id[index],
                  name: xiaoleiArray.name[index],
                  value: xiaoleiArray.value[index],
                  fid: xiaoleiArray.fid[index],
                  fidName: xiaoleiArray.fidName[index]
                }
                xiaoleiTempl[value.fid] += `
                  <div class="tag_container">
                    <input form='hidden_form_1' value='${value.id}' type="radio" name="chanpin_type_only_one" id="chanpin_type_${value.id}_${index}" class="check_tag chanpin_type_item">
                    <label for="chanpin_type_${value.id}_${index}" class="label_check_tag"><span><span>${value.name}</span></span></label>
                  </div>
                `.trim()
              })
            } else {
              $.each(xiaoleiArray.id, (index, item) => {
                const value = {
                  id: xiaoleiArray.id[index],
                  name: xiaoleiArray.name[index],
                  value: xiaoleiArray.value[index],
                  fid: xiaoleiArray.fid[index],
                  fidName: xiaoleiArray.fidName[index]
                }
                xiaoleiTempl[value.fid] += `
                  <div class="tag_container">
                    <input form='hidden_form_1' value='${value.id}' type="checkbox" name="chanpin_type_${value.name}" id="chanpin_type_${value.id}_${index}" class="check_tag chanpin_type_item">
                    <label for="chanpin_type_${value.id}_${index}" class="label_check_tag"><span><span>${value.name}</span></span></label>
                  </div>
                `.trim()
              })
            }

            // replace 渠道类型
            $('#qudao_leixing').empty().append(qudaoLeixingTempl)
            // replace 小类标签
            // 先去除当前所有小类
            $(`.chanpin_type_tag_wrap .tag_container`).each((index, item) => {
              $(item).remove()
            })
            // 循环对象，append对应内容

            $.each(xiaoleiTempl, (index, item) => {
              $(`.weui-cell[inori-replace-id="${index}"]`).append(item)
            })
          }).done((res) => {
            // 回填
            // 只有页面载入的时候需要回填
            // sessionStorage.setItem('need_to_rewrite', '1')
            const ifRewrite = sessionStorage.getItem('need_to_rewrite') === '1'
            if (ifRewrite && myValue !== undefined && myValue !== null && myValue !== '[]') {
              // try{
              //   myValue = JSON.parse(myValue)
              // } catch (e) {
              //   throw e
              // }
              // 即将回填，去除回填标志
              sessionStorage.setItem('need_to_rewrite', '0')
              for( let item of myValue ) {
                let name = item.name
                let value = item.value
                if (name === 'daikuan_local') {
                  // $("#city-picker").attr('value', value)
                  ;
                } else {
                  $(`[name='${name}'][value='${value}']`).prop('checked', true)
                }
              }
            }
          }).done((res) => {
            // 请求大类利息额度信息
            let dalei_addon = []
            let dalei_fetch_promise = []
            const ajaxURL = `${$('#new_fz_biaoqian').val()}`
            $.each($('.whole_line_label[inori-data]'), (index, item) => {
              const value = $(item).attr('inori-data')
              const promiseItem = new Promise((resolve, reject) => {
                $.ajax(ajaxURL, {
                  method: 'post',
                  data: {
                    daleiid: value
                  }
                }).fail((err) => {
                  debugger
                  reject(err)
                }).done((res) => {
                  if (!res.code || `${res.code}` !== '1') reject(new Error(JSON.stringify(res)))
                  else resolve(res)
                })
              })
              dalei_fetch_promise.push(promiseItem)
            })
            Promise.all(dalei_fetch_promise).then((data) => {
              $.each($('.whole_line_label[inori-data]'), (index, item) => {
                data[index].data.min_lx === null ? '0.00' : data[index].data.min_lx
                $(item).find('.inline_lixi').empty()
                $(item).find('.inline_lixi').append('<span></span>')
                $(item).find('.inline_lixi span').text(`${data[index].data.min_lx === null ? '0.00' : data[index].data.min_lx}%-${data[index].data.max_lx === null ? '0.00' : data[index].data.max_lx}% / ${data[index].data.min_ed === null ? '0' : data[index].data.min_ed}万-${data[index].data.max_ed === null ? '0' : data[index].data.max_ed}万`)
                $(item).find('.inline_lixi span').attr('data', `${data[index].data.min_lx === null ? '0.00' : data[index].data.min_lx}%-${data[index].data.max_lx === null ? '0.00' : data[index].data.max_lx}% / ${data[index].data.min_ed === null ? '0' : data[index].data.min_ed}万-${data[index].data.max_ed === null ? '0' : data[index].data.max_ed}万`)
                if (item.offsetTop !== $(item).find('.inline_lixi')[0].offsetTop) {
                  const maxWidth = $(item).width() - 70
                  $(item).find('.inline_lixi').css('max-width', maxWidth)
                }
                $(item).on('click', (evt) => {
                  const targetID = $(evt.target).attr('for')
                  if($(`#${targetID}`).prop('checked') === true) return
                  $.toptip(`${$(evt.target).find('.inline_lixi span').attr('data')}`, 'success')
                })
              })
            }).catch(err => {
              debugger
              $.toptip('产品类型利息数据更新失败', 'error')
              console.log(err)
            })
          })
        }
      })
      $('#city-picker').data('picker').open()
      $('#city-picker').data('picker').close()
      // 异步ajax函数已经触发
    })
  </script>
</body>
</html>
